package com.octant.testtcpudp;

import android.content.Context;
import android.util.Log;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

public class UdpServerRunnable implements Runnable {

    private String TAG = "UdpServerRunnable";

    private DatagramSocket  server;	//设置服务器套接字
    private int port = 8080;

    private String clientIp = "";
    private int clientPort = 0;

    public UdpServerRunnable(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    public String getClientIp() {
        return clientIp;
    }

    public int getClientPort() {
        return clientPort;
    }

    @Override
    public void run() {

        try {
            //1.创建服务器端DatagtamSocket，指定端口号
            server = new DatagramSocket(port);
            //2.创建数据报，用于接收客服端发送的数据
            byte[] data = new byte[1024];//创建字节数组，指定数据报的大小
            DatagramPacket packet = new DatagramPacket(data, data.length);//
            //3.接收客服端发送的消息
            while (true) {
                if (server == null){
                    break;
                }
                server.receive(packet);//此方法在收到数据之前会一直阻塞
                String ip = packet.getAddress().getHostName();
                int port = packet.getPort();
                if (ip.equals(clientIp)==false || port != clientPort){
                    clientIp = ip;
                    clientPort = port;
                    if (listener != null) {
                        listener.onUdpServerNewConnection(clientIp,clientPort);
                    }
                    Log.i(TAG,"onUdpServerNewConnection");
                }
                if (listener != null) {
                    listener.onUdpServerReceiveData(data, packet.getLength(),server.getPort(), ip, port);
                }
                Log.i(TAG,"onUdpServerReceiveData");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        close();
        if (listener != null) {
            listener.onUdpServerClose();
        }
        Log.i(TAG,"onUdpServerClose,");
    }

    public void sendData(final byte[] data, final String ip, final int port,ExecutorService cachedThreadPool){
        if (cachedThreadPool != null){
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //1.定义客服端的地址、端口号、数据
                        InetAddress address = InetAddress.getByName(ip);
                        //2.创建数据报，包含响应的数据信息
                        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
                        //3.响应客服端
                        server.send(packet);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //1.定义客服端的地址、端口号、数据
                        InetAddress address = InetAddress.getByName(ip);
                        //2.创建数据报，包含响应的数据信息
                        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
                        //3.响应客服端
                        server.send(packet);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    public void close(){
        if (server != null){
            server.close();
        }
        server = null;
    }

    private UdpServerListener listener;

    public void setListener(UdpServerListener listener) {
        this.listener = listener;
    }

    public interface UdpServerListener{
        void onUdpServerNewConnection(String clientIp,int clientPort);
        void onUdpServerReceiveData(byte[] data,int len,int port,String clientIp,int clientPort);
        void onUdpServerClose();
    }


}
